package com.third.device.mg.serialport.factory.autorail

import com.third.device.mg.serialport.utils.to2ByteH
import com.third.device.mg.serialport.utils.to2ByteL

/**
 * @Date 2022/1/13
 * Description:奥特威CRC校验码
 */
object AutorailsCRC {


    /**
     * 生成Int,自己转ByteArray
     */
    fun crcRTU(pushMsg: ByteArray) : Int {
        var crc = 0xffff
        val crcpoly = 0xA001
        var crcBit :Int
        pushMsg.forEach { src ->
            crc = crc xor (src.toInt() and 0xff)
            for (j in 0 until 8){
                crcBit = crc and 0x01
                crc = crc shr 1
                if (crcBit == 1){
                    crc = crc xor crcpoly
                }
            }
        }
        return crc
    }

    /**
     * Crc校验，低位前,高位后
     * @return [ByteArray] 低位前,高位后
     */
    fun crcRTU2L(pushMsg: ByteArray) : ByteArray {
        var crc = 0xffff
        val crcpoly = 0xA001
        var crcBit :Int
        pushMsg.forEach { src ->
            crc = crc xor (src.toInt() and 0xff)
            for (j in 0 until 8){
                crcBit = crc and 0x01
                crc = crc shr 1
                if (crcBit == 1){
                    crc = crc xor crcpoly
                }
            }
        }
        return crc.to2ByteL()
    }


    /**
     * Crc校验，高位前，低位后
     * @return [ByteArray] 高位前，低位后
     */
    fun crcRTU2H(pushMsg: ByteArray) : ByteArray {
        var crc = 0xffff
        val crcpoly = 0xA001
        var crcBit :Int
        pushMsg.forEach { src ->
            crc = crc xor (src.toInt() and 0xff)
            for (j in 0 until 8){
                crcBit = crc and 0x01
                crc = crc shr 1
                if (crcBit == 1){
                    crc = crc xor crcpoly
                }
            }
        }
        return crc.to2ByteH()
    }
}